#include "StdAfx.h"
#include "LitScriptStream.h"

namespace Lit
{
	ScriptStream::ScriptStream( const ScriptStream& rk )
	{
		mSize = rk.mSize;
		mStream = rk.mStream;
	}
	ScriptStream::ScriptStream(const std::string &fname, Lit::Stream::Access access )
	{
		mStream = NULL;
		mSize = 0;
		if( !fname.empty() )
		{
			fseek( mStream, 0, SEEK_END );
			mSize = ftell(mStream);
			fseek( mStream, 0, SEEK_SET );
		}
	}
	ScriptStream::~ScriptStream(){
		if( mStream ) fclose(mStream);
		mStream = NULL;
		mSize = 0;
	}


	size_t ScriptStream::size() const{ return mSize; }
	bool ScriptStream::open( const std::string &name, Access access ){ 
			
		mStream = fopen( name.c_str(), getCOpenMode( access ).c_str() );
		if( !mStream ) throw std::runtime_error(("Cannot open script binary stream '"+name+"'").c_str());
		return (mStream!=NULL);
	}
	void ScriptStream::close(){ 
		if( mStream ) fclose(mStream);
		mStream = NULL;
	}

	std::string ScriptStream::getCOpenMode( Access access ){
		std::string cmod = "rb";
		if( access == Stream::BinaryRead ) cmod = "rb";
		else if( access == Stream::BinaryWrite ) cmod = "wb";
		else if( access == Stream::TextRead ) cmod = "r";
		else if( access == Stream::TextWrite ) cmod = "w";
		return cmod;
	}
	ScriptStream& ScriptStream::read( size_t num_chars, std::string & out ){ 
		out.resize( num_chars+1, '\0' );
		fread( (void*)&out.at(0), sizeof(char), num_chars, mStream );
		return *this;
	}
	ScriptStream& ScriptStream::write( const std::string& str ){ 
		fwrite( &str.at(0), sizeof(char), str.size(), mStream );
		return *this;
	}
	ScriptStream& ScriptStream::readUntil( char c, std::string& out ){
		char t;
		out.clear();
		while( (t=fgetc(mStream)) != c )
		{
			out.append(1,t);
		}
		return *this;
	}
	bool ScriptStream::eof() const{ if( mStream ) return feof( mStream ); return true; }
	bool ScriptStream::valid() const{ if( !mStream ) return false; return true; }

	void ScriptStream::Write(const void *ptr, asUINT size) 
	{
		if( size == 0 || !mStream ) return; 
		fwrite(ptr, size, 1, mStream); 
	}
	void ScriptStream::Read(void *ptr, asUINT size) 
	{ 
		if( size == 0 || !mStream ) return; 
		fread(ptr, size, 1, mStream); 
	}
};